//
//  SupportMVM.swift
//  DianXia
//
//  Created by you&me on 2017/12/19.
//  Copyright © 2017年 you&me. All rights reserved.
//

import Foundation

//绑定的 机器的识别属相
struct RobotState {
    var iderfier = ""
    var isOpen = false
    var code = ""

}

class SupportVM {

    let provider = MoyaProvider<BCModuleApi>()
    let providerLoading = MoyaProvider<BCModuleApi>(plugins: [networkPlugin])
    let dispose = DisposeBag()
    var requestCount = 0
    var supportIdentity = 0
    var actionType = ""
    var robotCode = ""

    let isRobotOpen  = Variable(RobotState())
    let okUnlive = Variable(false)


    /// 申请补货 
    ///
    /// - Parameters:
    ///   - code: 机器码
    ///   - taskNo: 任务编码
    func support( _ code: String, _ taskNo: Int) {
        provider.rx.request(.applyReplenishment(code: code, userId: UserManager.shareManager.userId ?? "", taskNo: taskNo))
            .retry(3)
            .asObservable()
            .mapModel(SupportModel.self)
            .subscribe(onNext: { (supportModel) in
                self.dataManage(supportModel,"submitSupportSuccess")
            })
            .disposed(by: dispose)
    }
    /// 完成补货
    ///
    /// - Parameter code: 机器码
    func completeReplenishment(_ code: String) {
        self.robotCode = code
        providerLoading.rx.request(.doneReplenishment(code: code))
            .retry(3)
            .asObservable()
            .mapModel(SupportModel.self)
            .subscribe(onNext: { (supportModel) in
                self.dataManage(supportModel,"finishSupportSuccess")
            })
            .disposed(by: dispose)

    }
    /// 申请维修
    ///
    /// - Parameters:
    ///   - code: 机器码
    ///   - taskNo: 任务编码
    func repair(_ code: String, _ taskNo: Int) {
        provider.rx.request(.repair(code: code, userId: UserManager.shareManager.userId ?? "", taskNo: taskNo))
            .retry(3)
            .asObservable()
            .mapModel(SupportModel.self)
            .subscribe(onNext: { (supportModel) in
                self.dataManage(supportModel,"submitRepairSuccess")
            })
            .disposed(by: dispose)
    }

    /// 完成维修
    ///
    /// - Parameters:
    ///   - code: 机器码
    ///   - log: 日志
    func repairCompleteRequest(_ code: String, _ log: String) {
        self.robotCode = code
        providerLoading.rx.request(.RepairCompleteRequest(code: code, log: log))
            .retry(3)
            .asObservable()
            .mapModel(SupportModel.self)
            .subscribe(onNext: { (supportModel) in
                self.dataManage(supportModel,"finishRepairSuccess")
            })
            .disposed(by: dispose)
    }


    //数据处理
    fileprivate func dataManage(_ model: SupportModel, _ actionType: String) {
        guard model.msg == "success" else {
            return BCShowMessage.shareMessage.showTipMsg(model.result?.describe ?? "", time: 1)
        }
        self.supportIdentity = model.result?.identity ?? 0
        self.actionType = actionType
        self.requestCount = 0
        self.isOpen(actionType, self.supportIdentity)
    }

    //是否已经开机
    fileprivate func isOpen(_ actionType: String, _ identity: Int) {

        self.requestCount += 1
        provider.rx.request(.isRobotOpenRequest(actionType: actionType, identity: identity))
            .retry(3)
            .asObservable()
            .mapModel(SupportModel.self)
            .subscribe(onNext: { (supportModel) in
                guard supportModel.msg == "success" else {
                    return BCShowMessage.shareMessage.showTipMsg(supportModel.result?.describe ?? "", time: 1)
                }

                self.isRobotOpen.value.iderfier = actionType
                guard supportModel.result?.ifSuccess == 1 else {
                    if self.requestCount < 5{
                        self.isOpen(self.actionType, self.supportIdentity)
                    }else{
                        //失败
                        self.isRobotOpen.value.isOpen = false
                    }
                    return
                }
                //成功
                self.isRobotOpen.value.code = self.robotCode
                self.isRobotOpen.value.isOpen = true
            })
            .disposed(by: dispose)
    }

}

extension SupportVM {

    /// 退服
    ///
    /// - Parameters:
    ///   - code: 机器码
    ///   - reason: 退服原因
    func unliveRequest(_ code: String, _ reason: String) {
        provider.rx.request(.unlive(code: code, mobile: UserManager.shareManager.userMobile ?? "", reason: reason))
            .retry(3)
            .asObservable()
            .mapModel(SupportModel.self)
            .subscribe(onNext: { (supportModel) in
                guard supportModel.msg == "success" else {
                    self.okUnlive.value = false
                    return BCShowMessage.shareMessage.showTipMsg(supportModel.result?.describe ?? "", time: 1)
                }
                self.okUnlive.value = true
            })
            .disposed(by: dispose)
    }
}

extension SupportVM {

    /// 激活设备
    ///
    /// - Parameters:
    ///   - province: 省
    ///   - city: 市
    ///   - district: 区
    ///   - street: 街道
    ///   - room: 详细地址
    ///   - code: 机器码
    func activeRequest(_ province: String, _ city: String, _ district: String, _ street: String,_ room: String, _ code: String) {
        let lng = UserManager.shareManager.lng ?? ""
        let lat = UserManager.shareManager.lat ?? ""
        let point = "\(lng)，\(lat)"
        provider.rx.request(.active(point: point, province: province, city: city, district: district, street: street, room: room, code: code, mobile: UserManager.shareManager.userMobile ?? ""))
            .retry(3)
            .asObservable()
            .mapModel(SupportModel.self)
            .subscribe(onNext: { (supportModel) in
                guard supportModel.msg == "success" else {
                    return BCShowMessage.shareMessage.showTipMsg(supportModel.result?.describe ?? "", time: 1)
                }
                self.robotCode = code
                self.requestCount = 0
                self.activeisOKRequest(code)
            })
            .disposed(by: dispose)
    }

    /// 确定售卖机是否已经正确接收激活请求
    ///
    /// - Parameter code: 售卖机号码
    func activeisOKRequest(_ code: String)  {
        self.requestCount += 1
        provider.rx.request(.activeSuccess(code: code))
            .retry(3)
            .asObservable()
            .mapModel(SupportModel.self)
            .subscribe(onNext: { (supportModel) in
                guard supportModel.msg == "success" else {
                    return BCShowMessage.shareMessage.showTipMsg(supportModel.result?.describe ?? "", time: 1)
                }

                self.isRobotOpen.value.iderfier = "activeSuccess"
                guard supportModel.result?.ifSuccess == 1 else {
                    if self.requestCount < 5{
                        self.activeisOKRequest(self.robotCode)
                    }else{
                        //失败
                        self.isRobotOpen.value.isOpen = false
                    }
                    return
                }
                //成功
                self.isRobotOpen.value.code = self.robotCode
                self.isRobotOpen.value.isOpen = true
            })
            .disposed(by: dispose)
    }
}

struct SupportModel: HandyJSON {
    var msg: String?
    var result: SupportResult?
}

struct SupportResult: HandyJSON {
    var describe: String?
    var identity: Int?
    var ifSuccess: Int?

}
